﻿using iTool_Cetector.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace iTool_Cetector.Global
{
    public class iToolServiceStatusFileChange
    {
        public static readonly string _iToolServiceProcessPath = "/var/iTool/service.process";
        public static readonly string _iToolConnectorProcessPath = "/var/iTool/client.process";
        static readonly string _iToolProcessPath = "/var/iTool/x.process";

        public static readonly string serviceURL = $"{GlobalUtils.GatewayUrl.TrimEnd('/')}/service.process";
        public static readonly string clientURL = $"{GlobalUtils.GatewayUrl.TrimEnd('/')}/client.process";

        static FileChangeDetect iToolServiceListener;
        static GlobalStatus globalStatus;

        public static void Startup(GlobalStatus _globalStatus) {
            globalStatus = _globalStatus;
        }

        static iToolServiceStatusFileChange() 
        {
#if DEBUG
            _iToolProcessPath = "D:/iTool-Cetector/x.process";
            _iToolServiceProcessPath = "D:/iTool-Cetector/service.process";
            _iToolConnectorProcessPath = "D:/iTool-Cetector/client.process";
#endif

            try
            {
                iToolServiceListener = new FileChangeDetect(_iToolProcessPath, 2000);
                Dictionary<string, Action<string>> keyValues = new Dictionary<string, Action<string>>();
                keyValues.Add(Path.GetFileName(_iToolServiceProcessPath), iToolServiceListenerMethod);
                keyValues.Add(Path.GetFileName(_iToolConnectorProcessPath), iToolConnectorListenerMethod);
                iToolServiceListener.StartWaitResult(keyValues);
            }
            catch (Exception)
            {
            }
        }


        public static void iToolServiceListenerMethod(string value) 
        {
            try
            {
                Utils.Logger($"iToolServiceListenerMethod:{value}");

                var status = (ProcessStatusEnum)Enum.Parse(typeof(ProcessStatusEnum), value);

                // 向提交状态
                HttpContent content = new StringContent(value);

                switch (status)
                {
                    case ProcessStatusEnum.Staring:
                        new PluginsController().Upgrade("iTool-Server-Plugins");
                        break;
                    case ProcessStatusEnum.Stoping:
                        break;
                    case ProcessStatusEnum.Started:
                        new PluginsController().Upgrade("iTool-Server-Plugins");
                        _ = Task.Factory.StartNew(async () =>
                        {
                            await Task.Delay(2000);
                            globalStatus.IniInstances = false;
                        });
                        break;
                    case ProcessStatusEnum.StartError:
                    case ProcessStatusEnum.Stoped:
                        globalStatus.Instances = globalStatus.Instances.Where(item => item.Title != "iTool-Server").ToList();
                        break;
                    case ProcessStatusEnum.WaitingStopSignal:
                        break;
                    case ProcessStatusEnum.WaitingStartSignal:
                        break;

                    case ProcessStatusEnum.BeginStoped:
                    case ProcessStatusEnum.BeginStart:
                    case ProcessStatusEnum.BeginStop:
                        return;
                }

                HttpClient httpClient = CreateHttpClientObject(content);
                var task = httpClient.PostAsync(serviceURL, content);
                task.Wait(2000);
                if (task.IsCompleted)
                {

                }
            }
            catch (Exception)
            {
            }
        }








        public static void iToolConnectorListenerMethod(string value)
        {
            try
            {
                Utils.Logger($"iToolConnectorListenerMethod:{value}");

                var status = (ProcessStatusEnum)Enum.Parse(typeof(ProcessStatusEnum), value);

                // 向提交状态
                HttpContent content = new StringContent(value);

                switch (status)
                {
                    case ProcessStatusEnum.Staring:
                        _ = new PluginsController().Upgrade("iTool-Connector-Plugins");
                        break;
                    case ProcessStatusEnum.Stoping:
                        break;
                    case ProcessStatusEnum.Started:
                        _ = new PluginsController().Upgrade("iTool-Connector-Plugins");
                        _ = Task.Factory.StartNew(async () =>
                        {
                            await Task.Delay(2000);
                            globalStatus.IniInstances = false;
                        });
                        break;
                    case ProcessStatusEnum.StartError:
                    case ProcessStatusEnum.Stoped:
                        globalStatus.Instances = globalStatus.Instances.Where(item => item.Title != "iTool-Connector").ToList();
                        break;
                    case ProcessStatusEnum.WaitingStopSignal:
                        break;
                    case ProcessStatusEnum.WaitingStartSignal:
                        break;

                    case ProcessStatusEnum.BeginStart:
                    case ProcessStatusEnum.BeginStop:
                    case ProcessStatusEnum.BeginStoped:
                        return;
                }

                HttpClient httpClient = CreateHttpClientObject(content);
                var task = httpClient.PostAsync(clientURL, content);
                task.Wait(2000);
                if (task.IsCompleted)
                {

                }
            }
            catch (Exception)
            {
            }
        }

        public static HttpClient CreateHttpClientObject(HttpContent content)
        {

            //Utils.Logger($"CreateHttpClientObject");

            HttpClient httpClient = HttpClientFactory.Create();
            //content.Headers.Add("seed", GlobalUtils.SeedString);
            //content.Headers.Add("publicip", GlobalUtils.PublicIp);

            // 头部+入签名信息
            if (!string.IsNullOrWhiteSpace(GlobalUtils.SeedString))
            {
                content.Headers.Add("seed", GlobalUtils.SeedString);
            }

            content.Headers.Add("publicip", GlobalUtils.PublicIp);

            return httpClient;
        }
    }
}
